package org.rendao.auth.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.rendao.auth.model.UserDetail;
import org.rendao.auth.model.UserRole;
import org.rendao.auth.service.UserDetailService;
import org.rendao.exception.TBFError;
import org.rendao.exception.TBFException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.context.SecurityContextRepository;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class AuthenticationController {

	private static final Logger logger = Logger.getLogger(AuthenticationController.class);
	
	@Autowired
	@Qualifier("authenticationManager")
	AuthenticationManager authenticationManager;
	
	@Autowired
	SecurityContextRepository repository;
	
	@Autowired
	UserDetailService userDetailService;
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	@ResponseBody
	public UserDetail restfulLogin(@RequestBody String loginInfo, HttpServletRequest request, HttpServletResponse response) {
		String[] info = loginInfo.split(",");
		String username = info[0];
		String password = info[1];
		UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
				username, password);
		UserDetail user = null;
		Authentication auth = authenticationManager.authenticate(token);
		SecurityContext context = SecurityContextHolder.getContext();
		context.setAuthentication(auth);
		repository.saveContext(context, request, response);
		user = getUserDetail(auth); 
		return user;
	}

	@RequestMapping(value = "/get_user", method = RequestMethod.GET)
	@ResponseBody
	public UserDetail getCurrentUser() {
		 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	     return getUserDetail(auth);
	}
	
	@SuppressWarnings("unchecked")
	private UserDetail getUserDetail(Authentication authentication) {
		if(authentication instanceof AnonymousAuthenticationToken) {
			throw new TBFException(TBFError.AUTH_ERROR);
		}
		String username = ((User)authentication.getPrincipal()).getUsername();
		return userDetailService.getByName(username);
		
//	    Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) authentication.getAuthorities();
//	    List<UserRole> roles = new ArrayList<UserRole>();
//	    for(SimpleGrantedAuthority ga : authorities) {
//	    	String roleName = ga.getAuthority();
//	    	roles.add(new UserRole(roleName));
//	    }
//	    return new UserDetail(username, roles);
	}
}
